from django.contrib import admin
from .models import Category, Tag, Book, BookImage, BookReview


class BookImageInline(admin.TabularInline):
    model = BookImage
    extra = 1
    fields = ['image', 'alt_text', 'is_main', 'sort_order']


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'parent', 'level', 'sort_order', 'is_active']
    list_filter = ['level', 'is_active']
    search_fields = ['name', 'description']
    ordering = ['sort_order', 'name']
    prepopulated_fields = {'slug': ('name',)}
    
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if obj:
            form.base_fields['parent'].queryset = Category.objects.exclude(pk=obj.pk)
        return form


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ['name', 'color', 'created_at']
    search_fields = ['name']
    prepopulated_fields = {'slug': ('name',)}


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ['title', 'author', 'isbn', 'price', 'stock_quantity', 'is_active', 'created_at']
    list_filter = ['is_active', 'is_featured', 'categories', 'created_at']
    search_fields = ['title', 'author', 'isbn', 'publisher']
    prepopulated_fields = {'slug': ('title',)}
    filter_horizontal = ['categories', 'tags']
    inlines = [BookImageInline]
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'slug', 'author', 'publisher', 'isbn')
        }),
        ('价格库存', {
            'fields': ('price', 'discount_price', 'stock_quantity', 'min_stock_alert')
        }),
        ('内容信息', {
            'fields': ('description', 'content', 'categories', 'tags')
        }),
        ('媒体信息', {
            'fields': ('cover_image', 'preview_url')
        }),
        ('状态设置', {
            'fields': ('is_active', 'is_featured', 'sort_order')
        }),
        ('SEO信息', {
            'fields': ('meta_title', 'meta_description', 'meta_keywords'),
            'classes': ('collapse',)
        })
    )


@admin.register(BookReview)
class BookReviewAdmin(admin.ModelAdmin):
    list_display = ['book', 'user', 'rating', 'is_verified', 'created_at']
    list_filter = ['rating', 'is_verified', 'created_at']
    search_fields = ['book__title', 'user__email', 'title']
    readonly_fields = ['user', 'book', 'created_at']
